/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.www.app.edit;

import org.atomojo.www.app.edit.upload.UploadApplication;
import org.restlet.Application;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Cookie;
import org.restlet.data.Form;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.routing.Filter;
import org.restlet.routing.Router;
import org.restlet.routing.Template;

/**
 *
 * @author alex
 */
public class EditApplication extends Application {

   public EditApplication(Context context) {
      super(context);
      getTunnelService().setEnabled(false);
      
      for (String name : context.getParameters().getNames()) {
         String value = context.getParameters().getFirstValue(name);
         getLogger().info("Adding host parameter "+name+" -> "+value);
         context.getParameters().set(name,value,false);
      }
   }
   
   public Restlet createRoot() {
      Router router = new Router(getContext());
      router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
      final String base = getContext().getParameters().getFirstValue("app.url");
      getLogger().info("app.url="+base);
      Filter requireAuth = new Filter(getContext()) {
         protected int beforeHandle(Request request,Response response)
         {
            Cookie cookie = request.getCookies().getFirst("I");
            if (request.getChallengeResponse()==null || cookie==null) {
               String baseURL = base;
               if (baseURL==null) {
                  Object o = request.getAttributes().get("app.url");
                  if (o!=null) {
                     baseURL = o.toString();
                  } else {
                     getLogger().severe("app.url missing.");
                     response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                     return Filter.STOP;
                  }
               }
               Reference appRef = new Reference(baseURL);
               getLogger().info("Checking APP authentication proxy to "+appRef);
               Client client = new Client(getContext().createChildContext(),appRef.getSchemeProtocol());
               client.getContext().getAttributes().put("hostnameVerifier", org.apache.commons.ssl.HostnameVerifier.DEFAULT);
               Request appRequest = new Request(Method.GET,appRef);
               if (request.getChallengeResponse()!=null) {
                  appRequest.setChallengeResponse(request.getChallengeResponse());
               }
               Response appResponse = client.handle(appRequest);
               if (appResponse.getStatus().isSuccess()) {
                  return Filter.CONTINUE;
               } else if (appResponse.getChallengeRequests().size()>0) {
                  Form headers = (Form)appResponse.getAttributes().get("org.request.http.headers");
                  response.setStatus(appResponse.getStatus());
                  response.setEntity(appResponse.getEntity());
                  response.setChallengeRequests(appResponse.getChallengeRequests());
                  response.getAttributes().put("org.request.http.headers", headers);
                  response.setCookieSettings(appResponse.getCookieSettings());
                  return Filter.STOP;
               } else {
                  response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                  return Filter.STOP;
               }
            } else {
               return Filter.CONTINUE;
            }
         }
      };
      requireAuth.setNext(router);
      router.attach("/",new ClassResourceFinder(getContext(),EditApplication.class.getClassLoader(),EditApplication.class));
      router.attach("/upload",new UploadApplication(getContext()));
      router.attach("/app/",new APPProxy(getContext()));
      return requireAuth;
   }
}
